﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using TestDBData.EFContext;
using TestModel.Configuration;

namespace TestManage.Infrastructure.Extensions
{
    /// <summary>
    /// 表示IServiceCollection的扩展
    /// </summary>
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// 向应用程序添加服务并配置服务提供者
        /// </summary>
        /// <param name="services">Collection of service descriptors</param>
        /// <param name="configuration">Configuration of the application</param>
        /// <returns>Configured service provider</returns>
        public static IServiceProvider ConfigureApplicationServices(this IServiceCollection services, IConfiguration configuration)
        {
            //添加TestConfig配置参数
            services.ConfigureStartupConfig<TestConfig>(configuration.GetSection("Test"));
            services.AddHttpContextAccessor();
           
            //创建、初始化和配置引擎
            var engine = EngineContext.Create();
            engine.Initialize(services);
            IServiceProvider serviceProvider = engine.ConfigureServices(services, configuration);

            return serviceProvider;
        }

        /// <summary>
        /// 创建、绑定和注册指定的配置参数作为服务
        /// </summary>
        public static TConfig ConfigureStartupConfig<TConfig>(this IServiceCollection services, IConfiguration configuration) where TConfig : class, new()
        {
            if (services == null)
                throw new ArgumentNullException(nameof(services));

            if (configuration == null)
                throw new ArgumentNullException(nameof(configuration));

            //create instance of config
            var config = new TConfig();

            //bind it to the appropriate section of configuration
            configuration.Bind(config);

            //and register it as a service
            services.AddSingleton(config);

            return config;
        }

        /// <summary>
        /// 注册Http上下文存取器
        /// </summary>
        /// <param name="services">Collection of service descriptors</param>
        /// 服务描述符的集合
        public static void AddHttpContextAccessor(this IServiceCollection services)
        {
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        }

        ///// <summary>
        ///// Register base object context
        ///// </summary>
        ///// <param name="services">Collection of service descriptors</param>
        //public static void AddNopObjectContext(this IServiceCollection services)
        //{
        //    services.AddDbContext<NopObjectContext>(optionsBuilder =>
        //    {
        //        optionsBuilder.UseSqlServerWithLazyLoading(services);
        //    });
        //}
    }
}
